import React, {FC, useEffect, useMemo, useState} from 'react'
import {Space, Button, Popconfirm, Modal, message} from 'antd'
import {history} from 'umi'
import {PlusOutlined, ArrowUpOutlined} from '@ant-design/icons'
import AddVehicleInfoModal from './AddVehicleInfoModal'
import ReplaceFleetModal from './ReplaceFleetModal'
import {PageType} from '../constant'
import BatchUpload from '@/components/BatchUpload'
import SearchForm from '@/components/SearchForm'
import {
	getFleectGroup,
	getFleetErrorListPage,
	getFleetImportData,
	getHistoryFleet,
	getInfoCount,
	removeCar,
} from '@/service/customer/fleet'
import Styles from './index.less'
import {modalApi} from '@/utils/modalReq'
import CustomTable from '@/components/Table'
import {getDict} from '@/service/common/dict'

interface VehicleInfoType {
	pageType: any
	fleetId: string
}

const vehicleInfo: FC<VehicleInfoType> = (props) => {
	const {pageType, fleetId} = props
	const [loading, setLoading] = useState(false)
	const [total, setTotal] = useState(0)
	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)
	const [pagination, setPagination] = useState({
		current: 1,
		size: 10,
	})
	const [dataList, setDataList] = useState<any[]>([{}])
	// const [AddVehicle, setAddVehicle] = useState(false);
	const [addModalVisivle, setAddModalVisivle] = useState(false)
	const [replaceFleetVisivle, setReplaceFleetVisivle] = useState(false)
	const [historyFleetVisible, setHistoryFleetVisible] = useState(false)
	const [historyFleetDataList, setHistoryFleetDataList] = useState([])
	const [carNo, setCarNo] = useState('')
	const [historyFleetTableLoading, setHistoryFleetTableLoading] =
		useState(false)
	const [historyFleetId, setHistoryFleetId] = useState()
	const [replaceFleetData, setReplaceFleetData] = useState()
	const [historyFleetTotal, setHistoryFleetTotal] = useState(0)

	const [historyParams, setHistoryParams] = useState({
		current: 1,
		size: 10,
	})
	const [searchData, setSearchData] = useState({})
	const [fleetParams, setFleetParams] = useState({
		current: 1,
		size: 10,
	})
	const [dict, setDict] = useState<any>({
		carStatus: [],
	}) // 字典值
	const [allCarStatus, setAllCarStatus] = useState<any>([]) // 所有车辆状态

	// 获取字典
	useEffect(() => {
		getDict(
			{
				dictKeys: [
					'carStatus', // 车辆状态
				],
			},
			(res: any) => {
				setAllCarStatus(res?.carStatus)
				const data = JSON.parse(JSON.stringify(res))

				data.carStatus.forEach((item: any, index: number) => {
					if (item.dictValue === '已排车') {
						data.carStatus.splice(index, 1)
					}
				})
				data.carStatus.forEach((item: any, index: number) => {
					if (item.dictValue === '买商险') {
						data.carStatus.splice(index, 1)
					}
				})
				setDict(data)
			},
		)
	}, [])

	const orgId = useMemo(
		() => (history as any)?.location?.query.orgId,
		[history],
	)
	const FormItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'select',
					label: '车辆状态',
					name: 'carStatus',
					key: 'carStatus',
					keys: 'dictKey',
					title: 'dictValue',
					items: dict?.carStatus,
				},
				{
					type: 'input',
					key: 'carId',
					name: 'carId',
					label: '车辆id',
					rules: [
						{
							pattern: /^[0-9]*$/,
							message: '车辆id请输入数字',
						},
					],
				},
				{
					type: 'input',
					key: 'carNo',
					name: 'carNo',
					label: '车牌号',
				},
			],
		},
	]

	const getData = async () => {
		setLoading(true)
		const obj = {fleetId, ...fleetParams, ...searchData}
		const data = await getFleectGroup(obj).catch(() => setLoading(true))
		if (data.code === 0) {
			setDataList(data.data.records)
			setTotal(data.data.total)
		}
		setLoading(false)
	}
	useEffect(() => {
		if (fleetId) {
			getData()
		}
	}, [fleetId, fleetParams])

	// const onExport = async() => {
	//   fleetExport({pageNum:pagination.current,pageSize:pagination.pageSize})
	// }

	const getHistoryData = async () => {
		setHistoryFleetTableLoading(true)
		const obj = {carId: historyFleetId, ...historyParams}
		const data = await getHistoryFleet(obj)
		if (data.code === 0) {
			setHistoryFleetDataList(data.data.list.records)
			setHistoryFleetTotal(data.data.list.total)
			setCarNo(data.data.carNo)
		}
		setHistoryFleetTableLoading(false)
	}

	useEffect(() => {
		if (historyFleetId) {
			getHistoryData()
		}
	}, [historyFleetId, historyParams])

	const openEditPage = (dt: any) => {
		setReplaceFleetData(dt)
		setReplaceFleetVisivle(true)
	}

	const openHistory = async (dt: any) => {
		setHistoryFleetId(dt?.carId)
		setHistoryFleetVisible(true)
	}

	const [countData, setCountData] = useState<any>({})

	const getInfoCounts = () => {
		getInfoCount({fleetId}).then((res: any) => {
			setCountData(res.data)
		})
	}

	useEffect(() => {
		getInfoCounts()
	}, [])

	const onDelete = async (dt: any, index: any) => {
		const res = await removeCar({id: dt?.id})
		if (res.code === 0) {
			let newP = pagination
			if (index === 0 && pagination.current !== 1) {
				newP = {
					current: pagination.current - 1,
					size: pagination.size,
				}
				setPagination(newP)
			}
			getData()
			getInfoCounts()
			message.success(res.msg)
		}
	}

	const importData = async (data: any) => {
		const newData = data
		newData.fleetId = fleetId
		return getFleetImportData(newData)
		// .then((res: any) => {
		// 	if (res?.success) {
		// 		message.success(res.msg)
		// 		getData({})
		// 	} else {
		// 		message.error(res.msg)
		// 	}
		// 	setIsUploadModalOpen(() => false)
		// })
		// .catch((error: any) => {
		// 	message.error(error.msg)
		// 	setIsUploadModalOpen(() => false)
		// })
	}

	const getColnums: any[] = useMemo(() => {
		const col: any[] = [
			{
				title: '车辆id',
				dataIndex: 'carId',
				align: 'center',
				width: 110,
				render: (text: any, rocode: any) => (
					<Button
						type="link"
						onClick={() => {
							history.push({
								pathname: '/carMessage/list/view',
								query: {
									id: text,
									operationType: '1',
									vin: rocode.vin,
								},
							})
						}}>
						{text}
					</Button>
				),
			},
			{title: '车牌号', dataIndex: 'number', align: 'center', width: 110},
			{
				title: '品牌车系车型',
				dataIndex: 'carFullName',
				align: 'center',
				width: 120,
			},
			{
				title: '车辆状态',
				dataIndex: 'carStatus',
				align: 'center',
				render: (text: any) => (
					<>
						{dict?.carStatus.map((res: any) => {
							if (Number(res.dictKey) === text) {
								return <span>{res.dictValue}</span>
							}
							return ''
						})}
					</>
				),
				width: 100,
			},
			{title: '司机姓名', dataIndex: 'name', align: 'center', width: 100},
			{
				title: '司机id',
				dataIndex: 'expressId',
				align: 'center',
				width: 110,
				render: (text: any, rocode: any) => (
					<Button
						type="link"
						onClick={() => {
							history.push({
								pathname: '/driver/detail',
								query: {
									id: rocode?.driverId,
									status: rocode.status,
									orgId,
									type: 'detail',
								},
							})
						}}>
						{text}
					</Button>
				),
			},
			{
				title: '司机联系方式',
				dataIndex: 'tel',
				align: 'center',
				width: 120,
			},
		]

		if (pageType !== PageType.Detail) {
			col.push({
				title: '操作',
				dataIndex: 'operation',
				align: 'center',
				width: 200,
				render: (
					_: string,
					record: Record<string, string>,
					index: any,
				) => (
					<Space size={12}>
						<Button
							type="link"
							onClick={() => openEditPage(record)}>
							更换车队
						</Button>
						<Popconfirm
							placement="topLeft"
							title="确定要将该车辆移出车队吗？"
							onConfirm={() => onDelete(record, index)}
							okText="确定"
							cancelText="取消">
							<Button type="link">移除车队</Button>
						</Popconfirm>
						<Button type="link" onClick={() => openHistory(record)}>
							历史车队
						</Button>
					</Space>
				),
			})
		}
		return col
	}, [pageType, dataList])

	const getHistoryCloums: any[] = useMemo(
		() => [
			{title: '历史车队名称', dataIndex: 'fleetName', align: 'center'},
			{
				title: '车队长名称',
				dataIndex: 'fleetLeaderName',
				align: 'center',
			},
			{title: '加入车队时间', dataIndex: 'joinTime', align: 'center'},
			{
				title: '移出车队时间',
				dataIndex: 'removeTime',
				align: 'center',
				render: (text: string) =>
					text === '1970-01-01 00:00:00' ? '-' : text,
			},
		],
		[],
	)

	const errorColumns: any = [
		{
			title: '车辆id',
			dataIndex: 'carIds',
			align: 'center',
		},
		{
			title: '失败原因',
			dataIndex: 'reason',
			align: 'center',
		},
	]

	// const historyPaginationChange = (current: number, pageSize: number) => {
	// 	getHistoryData({current, pageSize})
	// 	setHistoryPagination({current, pageSize})
	// }

	return (
		<div className={Styles.vehicleInfo}>
			<div className={Styles.titleBox}>
				<div className={Styles.title}>车队小组信息</div>
				<div className={Styles.countBox}>
					{Object.keys(countData || []).map((item: any) => (
						<div className={Styles.item}>{`${
							allCarStatus[item - 1]?.dictValue
						} ${countData[item]}`}</div>
					))}
					{/* (<div className={Styles.item}>已分配车辆321</div>
          <div className={Styles.item}>可排车124台</div>
          <div className={Styles.item}>可发车100台</div>
          <div className={Styles.item}>用车中123台</div>
          <div className={Styles.item}>停运100台</div>) */}
				</div>
			</div>
			<div className={Styles.searchBox}>
				<SearchForm
					formLayout={{
						labelCol: {flex: '90px'},
						wrapperCol: {flex: '1'},
					}}
					formItems={FormItems}
					onReset={() => {
						setSearchData({})
						setFleetParams({
							current: 1,
							size: 10,
						})
					}}
					onFinish={(value) => {
						setSearchData(value)
						setFleetParams({
							current: 1,
							size: 10,
						})
					}}
				/>
			</div>
			<div className={Styles.content}>
				{pageType !== PageType.Detail && (
					<div className={Styles.btnList}>
						<Button
							icon={<PlusOutlined />}
							type="primary"
							ghost
							size="small"
							onClick={() => {
								setAddModalVisivle(true)
							}}>
							添加车辆
						</Button>
						<Button
							icon={<ArrowUpOutlined />}
							className={Styles.warning}
							ghost
							size="small"
							onClick={() => {
								setIsUploadModalOpen(true)
							}}>
							导入
						</Button>
						{/* <Button
              icon={<ArrowDownOutlined />}
              className={Styles.import}
              ghost
              size="small"
              onClick={() => {
                downloadDocumentUrl({
                  resourceId: '102',
                  queryDesc:
                    '车队小组信息导出,resourceId:102',
                  queryParam: searchValue,
                })
              }}
            >
              导出
            </Button> */}
					</div>
				)}
				<CustomTable
					params={fleetParams}
					columns={getColnums}
					total={total}
					pagination
					callback={(paginations: any) => {
						setFleetParams(paginations)
					}}
					loading={loading}
					dataSource={dataList}
				/>
			</div>
			<AddVehicleInfoModal
				addModalVisivle={addModalVisivle}
				setAddModalVisivle={setAddModalVisivle}
				callBack={() => {
					getData()
					getInfoCounts()
				}}
				idArr={dataList.map((item) => item.carId)}
				dict={dict}
			/>
			<ReplaceFleetModal
				value={replaceFleetData}
				replaceFleetVisivle={replaceFleetVisivle}
				setReplaceFleetVisivle={setReplaceFleetVisivle}
				callBack={() => {
					getData()
					getInfoCounts()
				}}
			/>

			<Modal
				title={
					carNo
						? `车辆历史车队信息（车牌号：${carNo}）`
						: '车辆历史车队信息'
				}
				destroyOnClose
				open={historyFleetVisible}
				onCancel={() => {
					setHistoryFleetVisible(false)
					setHistoryParams({
						current: 1,
						size: 10,
					})
				}}
				onOk={() => {
					setHistoryFleetVisible(false)
					setHistoryParams({
						current: 1,
						size: 10,
					})
				}}
				width={1000}>
				<div className="fleetHistoryModal">
					<div className="content">
						<CustomTable
							params={historyParams}
							columns={getHistoryCloums}
							total={historyFleetTotal}
							pagination
							callback={(paginations: any) => {
								setHistoryParams(paginations)
							}}
							loading={historyFleetTableLoading}
							dataSource={historyFleetDataList}
						/>
					</div>
				</div>
			</Modal>
			<BatchUpload
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				importData={importData}
				onTableList={getFleetErrorListPage}
				getListData={() => getData()}
				downloadUrl="customer/车辆导入模板.xlsx"
				uploadFileUrl={`${modalApi.customer}/fleet/import/car/check`}
				columns={errorColumns}
				sourceId={33}
				templateType="车辆导入模板"
			/>
		</div>
	)
}

export default vehicleInfo
